import _AllPrefabsNames from "src/Game/_prefabsName/_AllPrefabsNames";
import EssentialResUrls from "src/_T/Res/EssentialResUrls";
import ResLoad from "src/_T/Res/ResLoad";

/** 对象池管理管理 */
export default class MyObjectPool {

    private static _Instance: MyObjectPool;
    private constructor() { }
    //公开的方法
    public static get Instance(): MyObjectPool {
        if (!this._Instance) {
            this._Instance = new MyObjectPool();
            this._Instance.InitObjects();
        }
        return this._Instance;
    }
    /**预制体管理 */
    private PerfabObject: Map<string, Laya.Sprite3D> = new Map<string, Laya.Sprite3D>();
    /**对象池的列表 */
    private NotUserObjectPoolMap: Map<string, Array<Laya.Sprite3D>> = new Map<string, Array<Laya.Sprite3D>>();
    /**初始化对象池 */
    private InitObjects() {
        //this.AddPerfabToArray(_AllPrefabsNames.Sphere);
    }

    /**根据预制体名称添加 实例到对应列表中 */
    private AddPerfabToArray(PerfabObjectName: string) {
        let Url = EssentialResUrls.PrefabURL(PerfabObjectName);
        let Handler = Laya.Handler.create(this, this.LodeThreeObject, [PerfabObjectName, Url]);
        ResLoad.Load3D(Url, Handler);
    }
    /**加载回调 加载列表 */
    private LodeThreeObject(Name: string, Url: string) {
        let Obj = ResLoad.GetRes(Url) as Laya.Sprite3D;
        this.PerfabObject.set(Name, Obj);
        this.NotUserObjectPoolMap.set(Name, new Array<Laya.Sprite3D>());
    }
    /**创建对象 并添加到使用中的列表 */
    private CreatorObject(PerfabObjectName: string): Laya.Sprite3D {
        let TempObje: Laya.Sprite3D = null;
        if (this.PerfabObject.has(PerfabObjectName)) {
            TempObje = this.PerfabObject.get(PerfabObjectName).clone() as Laya.Sprite3D;
            if (TempObje == null) {
                console.log("克隆预制体对象失败");
            }
        }

        return TempObje;
    }
    /**获取对象池 对象 */
    public GetObjectByPool(PerfabObjectName: string, onCompleted: Laya.Handler = null): Laya.Sprite3D {
        let TempObje: Laya.Sprite3D = null;
        if (this.NotUserObjectPoolMap.has(PerfabObjectName)) {
            let List: Array<Laya.Sprite3D> = this.NotUserObjectPoolMap.get(PerfabObjectName);
            if (List.length > 0) {
                TempObje = List.pop();
            } else {
                TempObje = this.CreatorObject(PerfabObjectName);
            }
        }
        if (onCompleted) {
            onCompleted.args = [TempObje];
            onCompleted.run();
        }
        return TempObje;
    }

    /**移除对象到目标对象池中 */
    public RemoveObjectToPool(PerfabObjectName: string, ReObject: Laya.Sprite3D) {
        ReObject.removeSelf();
        if (this.NotUserObjectPoolMap.has(PerfabObjectName)) {
            let NotUserList: Array<Laya.Sprite3D> = this.NotUserObjectPoolMap.get(PerfabObjectName);
            NotUserList.push(ReObject);
        }
    }


}